package com.aia.ann.web;

import java.io.FileInputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.util.StringUtils;

import com.aia.ann.domain.PostcardWithBLOBs;
import com.aia.ann.service.ChiefService;
import com.opensymphony.xwork2.ActionSupport;

public class PicImageAction extends ActionSupport {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PicImageAction.class);

	private String id;
	private ChiefService chiefService;
	private static final long serialVersionUID = 1L;

	public String execute() throws Exception {
		FileInputStream fis = null;
		OutputStream os = null;
		PostcardWithBLOBs postcard = null;
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("image/jpeg");
			response.setHeader("Content-Disposition", "attachment; filename=\"ann_" +id+ "_y.jpg\"");
			os = response.getOutputStream();

			if (StringUtils.hasText(id)) {
				postcard = chiefService.selectPostcardByUserId(id);
			}

			if (postcard != null) {
				byte[] imgBin = postcard.getPSD_BIN();
				os.write(imgBin);
			} else {
				String str = ServletActionContext.getServletContext().getRealPath("/images/image.jpg");
				fis = new FileInputStream(str);
				IOUtils.copy(fis, os);
			}
		} catch (javax.imageio.IIOException iioe) {
			if (logger.isDebugEnabled()) {
				logger.debug("execute()"); //$NON-NLS-1$
			}
		} finally {
			IOUtils.closeQuietly(fis);
			if (os != null) {
				os.flush();
				IOUtils.closeQuietly(os);
			}
		}
		return null;
	}

	public void setChiefService(ChiefService chiefService) {
		this.chiefService = chiefService;
	}

	public ChiefService getChiefService() {
		return chiefService;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

}
